//http.ts
import { getItem } from '@/utils/local'
import axios, { AxiosRequestConfig } from 'axios'
import NProgress from 'nprogress'
import { useAuthStore } from '@/store/main'
import router from '@/router'

// 设置请求头和请求路径
axios.defaults.baseURL = 'http://127.0.0.1:7001'
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    if(getItem('token')){
      (config.headers as any).Authorization = `${getItem('token')}`
    }
    return config
  },
  (error) => {
    return error
  }
)
// 响应拦截
axios.interceptors.response.use((res) => {
  const authStore = useAuthStore()

  // if (res.data.code === 111) {
  //   sessionStorage.setItem('token', '')
  //   // token过期操作
  // }
  if(res.status === 401){
    // 刷新token
    authStore.reToken(getItem('token'))
  }
  return res
},(err)=>{
  if(err.response && err.response.data){
    const status = err.response.status
    const msg = err.response.data.message
    const code = err.response.data.code
    if(code === 10003){
      window.$message.error('登录过期，请重新登录')
      router.push('/login')
    }else if(code ===10001){
      window.$message.error('令牌错误，请重新登录')
      router.push('/login')
    }else{
      window.$message.error(`statusCode:${status},Message:${msg}`)
    }
  }else{
    window.$message.error(`${err}`)
  }
  return Promise.reject(err)
})

interface ResType<T> {
  code: number
  data?: T
  msg: string
  err?: string
}
interface Http {
  get<T>(url: string, params?: unknown): Promise<ResType<T>>
  post<T>(url: string, params?: unknown): Promise<ResType<T>>
  upload<T>(url: string, params: unknown): Promise<ResType<T>>
  download(url: string): void
}

const http: Http = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .get(url, { params })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  upload(url, file) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, file, {
          headers: { 'Content-Type': 'multipart/form-data' },
        })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  download(url) {
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = url
    iframe.onload = function () {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  },
}
export default http
